<template>
    <el-menu default-active="0" mode="horizontal" class="bar">

        <el-tooltip effect="light" content="上一页" placement="bottom" show-after="1000">
            <el-button @click="prev">
                <go-start :theme="iconConf.theme" :size="iconConf.size" fill="#333"
                    :strokeWidth="iconConf.strokeWidth" />
                上一页
            </el-button>
        </el-tooltip>

        <el-tooltip effect="light" content="下一页" placement="bottom" show-after="1000">
            <el-button @click="next">
                下一页
                <go-end :theme="iconConf.theme" :size="iconConf.size" fill="#333" :strokeWidth="iconConf.strokeWidth" />
            </el-button>
        </el-tooltip>

        <el-select v-model="chapterIndex" placeholder="Select" style="width: 150px" v-if="nwStore.book?.spine">
            <template #prefix>
                章节：
            </template>
            <el-option v-for="(item, i) in nwStore.book.spine.items" :key="i"
                :label="i + ' / ' + (nwStore.book.spine.items.length - 1)" :value="i" />
        </el-select>

        <el-tooltip effect="light" content="书签" placement="bottom" show-after="1000">

            <el-popover placement="top" :width="200" trigger="hover" title="快捷菜单">
                <template #reference>
                    <el-button @click="isFunc = true">
                        <bookmark-one :theme="iconConf.theme" :size="iconConf.size" fill="#333"
                            :strokeWidth="iconConf.strokeWidth" />
                    </el-button>
                </template>


                <div style="display: flex;flex-direction: column; flex-wrap: wrap;align-items: center;gap: 8px">
                    <el-button plain @click="addBookmark">添加书签</el-button>
                    <el-button link type="primary"
                        v-for="(bookmark, index) in Array.from(nwStore.bookmarkMap.entries())"
                        @click="goBookmark(bookmark[1])">{{ '书签：' + bookmark[0] }}</el-button>
                </div>

            </el-popover>
        </el-tooltip>

        <!-- <el-button @click="test">-----------------</el-button> -->


    </el-menu>


    <el-dialog v-model="isFunc" title="书签" width="500" style="border-radius: 10px;">
        <el-card class="card" shadow="never">

            <div style="display: flex;flex-wrap: wrap;align-items: center;gap: 8px">

                <!-- :row-class-name="tableRowClassName" -->
                <el-table :data="Array.from(nwStore.bookmarkMap.entries())" style="width: 100%" border>
                    <el-table-column label="书签名称（不可重复）" width="165">
                        <template #default="scope">
                            {{ scope.row[0] }}
                        </template>
                    </el-table-column>

                    <el-table-column fixed="right" label="操作">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="goBookmark(scope.row[1])">跳转书签</el-button>
                            <el-button link type="primary" size="small"
                                @click="delBookmark(scope.row[0])">删除书签</el-button>
                            <el-button link type="primary" size="small"
                                @click="updateBookmark(scope.row[0])">修改名称</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-button plain @click="addBookmark">添加书签</el-button>
                <!-- <el-button plain @click="tidyBookmark">整理书签</el-button> -->

                <el-button @click="() => {
                    nwStore.savePersistedData()
                    ElMessage.success({
                        showClose: true,
                        message: '已保存书签及必要设置'
                    });
                }">保存书签</el-button>
                
                <el-tooltip effect="light" placement="bottom"
                    :content="'该设置会影响自动书签，既书签 \'' + nwStore.Auto_Bookmark_Name + '\' ,该取消功能可能导致阅读位置丢失'">
                    <el-button v-if="nwStore.automaticBookMark" type="primary" plain @click="nwStore.automaticBookMark = false">自动书签(已启用)</el-button>
                    <el-button v-else type="info" plain @click="nwStore.automaticBookMark = true">自动书签(未启用)</el-button>
                </el-tooltip>

                

            </div>
        </el-card>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="isFunc = false">关闭窗口</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script setup lang="ts">
import { GoStart, GoEnd, BookmarkOne } from '@icon-park/vue-next';
import { useBaseStore } from '@/stores/baseStore';
import { useNWStore } from '@/stores/nwStore'
import { ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce, watchOnce } from '@/util/util.js'

const baseStore = useBaseStore();
const nwStore = useNWStore();

const iconConf = baseStore.getIconConf
const de_saveNWStore = debounce(nwStore.savePersistedData, 1000)

const chapterIndex = ref('未识别')
const isFunc = ref(false)

watchOnce(
    () => nwStore.rendition,
    () => {
        if (nwStore.bookmarkMap.has(nwStore.Auto_Bookmark_Name)) {
            goBookmark(nwStore.bookmarkMap.get(nwStore.Auto_Bookmark_Name))
        }
    }
)

watch(
    () => nwStore.rendition?.location?.start,
    () => {
        try {
            chapterIndex.value = nwStore.rendition.location.start.index
            autoBookmark()
        } catch {
            console.warn("NWFooterBar - 监听异常")
        }
    }
)

watch(
    () => chapterIndex.value,
    () => {
        if (chapterIndex.value !== nwStore.rendition.location.start.index) {
            const href = nwStore.book.spine.items[chapterIndex.value].href;
            nwStore.rendition.display(href)
        }
    }
)


const prev = function () {
    nwStore.rendition.prev()
}
const next = function () {
    nwStore.rendition.next()
}

const validator = function (inputValue) {
    if (inputValue === null) return '输入为空！';
    if (nwStore.bookmarkMap.has(inputValue)) {
        return '该书签已存在！';
    }
    return true;
}
const goBookmark = function (cfi) {
    nwStore.rendition.display(cfi)
}
const addBookmark = function () {
    const location = nwStore.rendition.location.start;

    console.log(location.cfi);

    ElMessageBox.prompt('为书签命名', '添加书签', {
        confirmButtonText: '添加书签',
        cancelButtonText: '取消',
        inputValidator: validator,
        inputErrorMessage: 'Invalid Email',
    })
        .then(({ value: input }) => {
            nwStore.bookmarkMap.set(input, location.cfi)
            ElMessage({
                type: 'success',
                message: "添加书签 '" + input + " ' 成功",
            })
        })
        .catch((err) => {
            console.log(err);
            if (err === 'cancel') return;
            ElMessage({
                type: 'error',
                message: '异常！！！',
            })
        })
        .finally(
            () => de_saveNWStore()
        )

}
const delBookmark = function (bookmark) {
    nwStore.bookmarkMap.delete(bookmark);
    de_saveNWStore()
}
const updateBookmark = function (bookmark) {
    ElMessageBox.prompt('为书签命名', '修改书签', {
        confirmButtonText: '提交修改',
        cancelButtonText: '取消',
    })
        .then(({ value: input }) => {

            const newMap = new Map();
            for (let [key, val] of nwStore.bookmarkMap) {
                if (key === bookmark) {
                    newMap.set(input, val);
                    continue;
                }
                newMap.set(key, val);
            }
            nwStore.bookmarkMap = newMap;

            // const location = nwStore.bookmarkMap.get(bookmark)
            // nwStore.bookmarkMap.delete(bookmark)
            // nwStore.bookmarkMap.set(input, location)

            ElMessage({
                type: 'success',
                message: "修改书签 '" + bookmark + " -> " + input + " ' 成功",
            })
        })
        .catch((err) => {
            console.log(err);
            if (err === 'cancel') return;
            ElMessage({
                type: 'error',
                message: '异常！！！',
            })
        })
        .finally(() => {
            de_saveNWStore()
        })
}
const autoBookmark = function () {
    if (nwStore.automaticBookMark) {
        nwStore.bookmarkMap.delete(nwStore.Auto_Bookmark_Name)
        nwStore.bookmarkMap.set(nwStore.Auto_Bookmark_Name, nwStore.rendition.location.start.cfi)
        console.log('------------');
        de_saveNWStore()
    }
}
</script>

<style scoped>
.bar {
    -webkit-app-region: drag;
    padding-left: 5%;
    align-items: center;
    border-bottom: none !important;
    gap: 10px;
    height: 100%;
    padding-top: 15px;
    padding-bottom: 5px;
    box-shadow: var(--el-box-shadow-lighter);
    z-index: 1;
    width: 100%;
}

.bar * {
    -webkit-app-region: no-drag;
}

.card {
    width: 450px;
    border: none;
}

.warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-3);
    /* background-color: var(--el-color-warning-light-3); */
}
</style>